﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AtletIS.Shared.Entities;
using AtletIS.Shared.Data;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using System.Globalization;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.Forms
{
    public partial class frmMacFinishImport : Form
    {
        private DisciplineListEntity _discipline;
        private DataTable dtImport;
        private string file;
        private double numWind;
        private DisciplineListTableAdapter taDisciplineList = new DisciplineListTableAdapter();
        private PerformancesTableAdapter taPerformances = new PerformancesTableAdapter();
        private ExtTextsTableAdapter taExtTexts = new ExtTextsTableAdapter();

        #region Ctor

        public frmMacFinishImport(DisciplineListEntity discipline)
        {
            InitializeComponent();

            this._discipline = discipline;
            this.Icon = Properties.Resources.AtletIS64;
        }

        #endregion

        // Form Load
        private void frmMacFinishImport_Load(object sender, EventArgs e)
        {
            this.lblTitle.Text += ": " + _discipline.Name.ToString() + " (" + _discipline.ID.ToString() + ")";

            if (_discipline.DisciplineCode == Globals.SprintCode)
                this.rbLanes.Checked = true;

            if (_discipline.DisciplineCode == Globals.LongRunCode)
                this.rbStartNumber.Checked = true;
        }

        // Open file
        private void tsbOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Title = "Vyberte súbor pre import";
            openDialog.Filter = "Textové súbory|*.txt";

            if (openDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                numWind = -100.00;

                file = openDialog.FileName;
                tsslFile.Text = "Súbor: " + file;

                #region SprintCode

                if (this.rbLanes.Checked)
                {
                    try
                    {
                        dgvImport.DataSource = null;

                        lblWind.Visible = true;
                        lblWind.Text = string.Empty;

                        dtImport = this.InLanes();

                        StreamReader macFinishReader = new StreamReader(file);
                        string textFile = macFinishReader.ReadToEnd();
                        string[] textLines = textFile.Split(new Char[] { '\n' });

                        // Performances
                        for (int i = 2; i < textLines.Length - 1; i++)
                        {
                            string[] textValues = textLines[i].Split('\t'); //new Char[] { '\t' });

                            dtImport.Rows.Add();
                            dtImport.Rows[dtImport.Rows.Count - 1]["Poradie"] = Convert.ToInt32(textValues[0]);
                            dtImport.Rows[dtImport.Rows.Count - 1]["Dráha"] = Convert.ToInt32(textValues[1]);
                            dtImport.Rows[dtImport.Rows.Count - 1]["Výkon"] = textValues[2];
                        }

                        dgvImport.DataSource = dtImport;

                        // Wind
                        string[] firstRow = textLines[0].Split('\t');
                        if (firstRow[1].Contains(":"))
                        {
                            string[] wind = firstRow[1].Split(':');
                            lblWind.Text = "w: " + wind[1].Trim();

                            double.TryParse(wind[1].Trim().Replace("m/s", string.Empty).Replace("+", string.Empty), out numWind);
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Importný súbor nemá správny formát.", "MacFinish Import");
                    }
                }

                #endregion

                #region LongRunCode

                if (this.rbStartNumber.Checked)
                {
                    try
                    {
                        dgvImport.DataSource = null;
                        
                        lblWind.Visible = false;
                        dtImport = this.NoLanes();

                        StreamReader macFinishReader = new StreamReader(file);
                        string textFile = macFinishReader.ReadToEnd();
                        string[] textLines = textFile.Split(new Char[] { '\n' });

                        for (int i = 2; i < textLines.Length - 1; i++)
                        {
                            string[] textValues = textLines[i].Split('\t'); //new Char[] { '\t' });
                            if (textValues != null && textValues.Length == 6 && !string.IsNullOrEmpty(textValues[3]))
                            {
                                dtImport.Rows.Add();
                                dtImport.Rows[dtImport.Rows.Count - 1]["Poradie"] = Convert.ToInt32(textValues[0]);
                                dtImport.Rows[dtImport.Rows.Count - 1]["Št. číslo"] = Convert.ToInt32(textValues[3]);
                                dtImport.Rows[dtImport.Rows.Count - 1]["Výkon"] = textValues[2];
                            }
                        }

                        dgvImport.DataSource = dtImport;
                    }
                    catch
                    {
                        MessageBox.Show("Importný súbor nemá správny formát.", "MacFinish Import");
                        dgvImport.DataSource = null;
                    }
                }

                #endregion
            }
        }

        // Import
        private void tsbImport_Click(object sender, EventArgs e)
        {
            if (dgvImport.DataSource == null)
            {
                MessageBox.Show("Najskôr vyberte súbor na import, prosím.", "MacFinish Import", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            try
            {
                aDbDataSet.PerformancesDataTable dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(_discipline.ID); // taPerformances.GetByDisciplineListId(discipline.ID);
                foreach (DataRow drPerformance in dtPerformances.Rows)
                {
                    if (this.rbLanes.Checked)
                    {
                        DataRow[] drCurrentImport = dtImport.Select("[Dráha] = " + drPerformance["Lane"].ToString());
                        if (drCurrentImport.Length > 0)
                        {
                            if (drCurrentImport[0]["Výkon"].ToString() == "DNF")
                            {
                                drPerformance["Rank"] = 0;
                                drPerformance["Result"] = 0;
                                drPerformance["Code"] = 3;
                            }
                            else if (drCurrentImport[0]["Výkon"].ToString() == "DNS")
                            {
                                drPerformance["Rank"] = 0;
                                drPerformance["Result"] = 0;
                                drPerformance["Code"] = 4;
                            }
                            else if (drCurrentImport[0]["Výkon"].ToString() == "DIS")
                            {
                                drPerformance["Rank"] = 0;
                                drPerformance["Result"] = 0;
                                drPerformance["Code"] = 1;
                            }
                            else
                            {
                                drPerformance["Rank"] = drCurrentImport[0]["Poradie"];

                                string[] time = drCurrentImport[0]["Výkon"].ToString().Split('.', ':');
                                TimeSpan tsResult = this.StringToTimespan(time);
                                drPerformance["Result"] = tsResult.Milliseconds / 10 + tsResult.Seconds * 100 + tsResult.Minutes * 100 * 100 + tsResult.Hours * 100 * 100 * 100;
                            }
                        }
                    }

                    if (this.rbStartNumber.Checked)
                    {
                        DataRow[] drCurrentImport = dtImport.Select("[Št. číslo] = " + drPerformance["StartNumber"].ToString());
                        if (drCurrentImport.Length > 0)
                        {
                            if (drCurrentImport[0]["Výkon"].ToString() == "DNF")
                            {
                                drPerformance["Rank"] = 0;
                                drPerformance["Result"] = 0;
                                drPerformance["Code"] = 3;
                            }
                            else if (drCurrentImport[0]["Výkon"].ToString() == "DNS")
                            {
                                drPerformance["Rank"] = 0;
                                drPerformance["Result"] = 0;
                                drPerformance["Code"] = 4;
                            }
                            else if (drCurrentImport[0]["Výkon"].ToString() == "DIS")
                            {
                                drPerformance["Rank"] = 0;
                                drPerformance["Result"] = 0;
                                drPerformance["Code"] = 1;
                            }
                            else
                            {
                                drPerformance["Rank"] = drCurrentImport[0]["Poradie"];

                                string[] time = drCurrentImport[0]["Výkon"].ToString().Split('.', ':');
                                TimeSpan tsResult = this.StringToTimespan(time);
                                drPerformance["Result"] = tsResult.Milliseconds / 10 + tsResult.Seconds * 100 + tsResult.Minutes * 100 * 100 + tsResult.Hours * 100 * 100 * 100;
                            }
                        }
                    }
                }

                taPerformances.Update(dtPerformances);

                // Ulozi vietor
                if (lblWind.Visible & lblWind.Text != string.Empty)
                {
                    aDbDataSet.ExtTextsDataTable dtExtTexts = DatabaseHelper.GetExtTextsByDisciplineListIdActive(_discipline.ID); // taExtTexts.GetByDiscListId(discipline.ID);

                    aDbDataSet.DisciplineListRow drDisciplineList = (aDbDataSet.DisciplineListRow)DatabaseHelper.GetDisciplineListById(_discipline.ID).Rows[0];
                    aDbDataSet.ExtTextsCodesRow extTextsCodesRow = (aDbDataSet.ExtTextsCodesRow)DatabaseHelper.GetExtTextsCodesById(2).Rows[0];

                    aDbDataSet.ExtTextsRow drNewExtText = dtExtTexts.AddExtTextsRow(null, drDisciplineList, Header: "w",
                            Num1: 0, Num2: 0, Text1: lblWind.Text, Text2: null,
                            WebId: 0, Active: true, Sync: false, Modified: DateTime.Now, parentExtTextsCodesRowByFK_ExtTexts_ExtTextsCodes: extTextsCodesRow, VersionInfo:null);
                    
                    taExtTexts.Update(drNewExtText);

                    if (numWind > -100.00)
                    {
                        drDisciplineList.Wind = numWind;
                        taDisciplineList.Update(drDisciplineList);
                    }
                }

                // Update [status] = ukoncena
                Helpers.StatusHelper.UpdateStatus(_discipline, Globals.StatusFinished);
                if (Globals.ActiveDiscipline != null)
                    Globals.ActiveDiscipline.Status = Globals.StatusFinished;

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "MacFinish Import", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // Close
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region Private methods

        private DataTable InLanes()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Poradie", typeof(int));
            dt.Columns.Add("Dráha", typeof(int));
            dt.Columns.Add("Výkon", typeof(string));

            return dt;
        }

        private DataTable NoLanes()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("Poradie", typeof(int));
            dt.Columns.Add("Št. číslo", typeof(int));
            dt.Columns.Add("Výkon", typeof(string));

            return dt;
        }

        private TimeSpan StringToTimespan(string[] time)
        {
            if (time.Length == 2)
            {
                int seconds = Convert.ToInt32(time[0].Trim());
                int hundreds = Convert.ToInt32(time[1].Trim());
                return new TimeSpan(0, 0, 0, seconds, hundreds * 10);
            }
            else if (time.Length == 3)
            {
                int minutes = Convert.ToInt32(time[0].Trim());
                int seconds = Convert.ToInt32(time[1].Trim());
                int hundreds = Convert.ToInt32(time[2].Trim());
                return new TimeSpan(0, 0, minutes, seconds, hundreds * 10);
            }
            else if (time.Length == 4)
            {
                int hours = Convert.ToInt32(time[0].Trim());
                int minutes = Convert.ToInt32(time[1].Trim());
                int seconds = Convert.ToInt32(time[2].Trim());
                int hundreds = Convert.ToInt32(time[3].Trim());
                return new TimeSpan(0, hours, minutes, seconds, hundreds * 10);
            }
            else
            {
                return new TimeSpan();
            }
        }

        #endregion

    }
}
